﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ScannerWatcher.Models;
using System.Runtime.InteropServices;
using ScannerWatcher.Service;
using System.Collections.Specialized;
using Newtonsoft.Json;
using System.IO;
using NPOI.XWPF.UserModel;
using PdfSharp.Pdf.IO;
using NPOI_2003.HWPF;
using CaseManagerLibrary.Models;
using CaseManagerLibrary.Auth;

namespace ScannerWatcher
{
    public partial class FileItem : UserControl
    {
        public event EventHandler OnUndefinedClick;
        public event EventHandler OnCategoryClick;
        private case_question_category undefinedCategory;

        public AddDto Category { get; set; }

        public FileItem()
        {
            InitializeComponent();

            SetCaseList(CaseHelper.CaseList);

            Category = new AddDto();

            this.lblTip.Visible = false;
        }

        public int No
        {
            get
            {
                if (this.lblNo.Text.Length == 0)
                {
                    return 0;
                }
                else
                {
                    return Convert.ToInt32(this.lblNo.Text);
                }
            }
            set
            {
                this.lblNo.Text = value.ToString();
            }
        }
        public string FileName
        {
            get
            {
                return this.txtFileName.Text;
            }
            set
            {
                this.txtFileName.Text = value;
            }
        }

        public string FilePath { get; set; }

        private string fileType = "";
        public string FileType
        {
            get
            {
                return fileType;
            }
            set
            {
                this.fileType = value;

                if (value == "word")
                {
                    this.pbDocType.Image = Properties.Resources.word;
                }
                else if (value == "pdf")
                {
                    this.pbDocType.Image = Properties.Resources.pdf;
                }
                else
                {
                    this.pbDocType.Image = Properties.Resources.file;
                }
            }
        }

        public caseinfo CaseInfo
        {
            get
            {
                if (this.cmbCase.SelectedIndex > 0)
                {
                    var caseinfo = CaseHelper.CaseList[this.cmbCase.SelectedIndex - 1];
                    return caseinfo;
                }
                else
                {
                    return null;
                }
            }
            set
            {
                if (value != null)
                {
                    this.cmbCase.SelectedIndex = CaseHelper.CaseList.IndexOf(value) + 1;


                }
                else
                {
                    this.cmbCase.SelectedIndex = -1;
                }
            }
        }

        private case_question_category parentNode;
        public case_question_category ParentNode
        {
            get => parentNode;
            set
            {
                if (value != null)
                {
                    parentNode = value;

                    RefreshCategory();
                }
            }
        }
        //public string CategoryId { get; set; }

        //public string CategoryName
        //{
        //    get
        //    {
        //        if (categoryType == "undefined")
        //        {
        //            return btnUndefined.Text;
        //        }
        //        else
        //        {
        //            return btnCategory.Text.Replace("归类到：", "");
        //        }
        //    }
        //    set
        //    {
        //        btnCategory.Text = "归类到：" + value;

        //        if (value == "")
        //        {
        //            this.btnCategory.Width = 75;
        //        }
        //    }

        //}

        //public string CategoryType
        //{
        //    get => categoryType;
        //    set
        //    {
        //        if (value == "undefined")
        //        {
        //            categoryType = "undefined";
        //            this.btnUndefined.BackColor = Color.DodgerBlue;
        //            this.btnUndefined.ForeColor = Color.White;
        //            this.btnUndefined.FlatAppearance.BorderColor = Color.SteelBlue;
        //            this.btnCategory.BackColor = System.Drawing.SystemColors.Control;
        //            this.btnCategory.ForeColor = System.Drawing.SystemColors.ControlText;
        //            this.btnCategory.FlatAppearance.BorderColor = Color.LightGray;

        //        }
        //        else
        //        {
        //            categoryType = "category";
        //            this.btnUndefined.BackColor = System.Drawing.SystemColors.Control;
        //            this.btnUndefined.ForeColor = System.Drawing.SystemColors.ControlText;
        //            this.btnUndefined.FlatAppearance.BorderColor = Color.LightGray;
        //            this.btnCategory.BackColor = Color.DodgerBlue;
        //            this.btnCategory.ForeColor = Color.White;
        //            this.btnCategory.FlatAppearance.BorderColor = Color.SteelBlue;
        //        }

        //        this.Refresh();
        //    }
        //}

        //private string undefinedCategoryId = "";
        //private string categoryType = "undefined";

        public void RefreshCategory()
        {
            if (parentNode != null)
            {
                if (parentNode.name == "未归类")
                {
                    this.btnUndefined.BackColor = Color.DodgerBlue;
                    this.btnUndefined.ForeColor = Color.White;
                    this.btnUndefined.FlatAppearance.BorderColor = Color.SteelBlue;
                    this.btnCategory.BackColor = System.Drawing.SystemColors.Control;
                    this.btnCategory.ForeColor = System.Drawing.SystemColors.ControlText;
                    this.btnCategory.FlatAppearance.BorderColor = Color.LightGray;

                    btnCategory.Text = "归类到：";
                    this.btnCategory.Width = 75;
                }
                else
                {
                    this.btnUndefined.BackColor = System.Drawing.SystemColors.Control;
                    this.btnUndefined.ForeColor = System.Drawing.SystemColors.ControlText;
                    this.btnUndefined.FlatAppearance.BorderColor = Color.LightGray;
                    this.btnCategory.BackColor = Color.DodgerBlue;
                    this.btnCategory.ForeColor = Color.White;
                    this.btnCategory.FlatAppearance.BorderColor = Color.SteelBlue;

                    btnCategory.Text = "归类到：" + parentNode.name;
                }
            }
        }

        private void btnUndefined_Click(object sender, EventArgs e)
        {
            //CategoryType = "undefined";
            //CategoryId = "";
            //CategoryName = "";
            ParentNode = undefinedCategory;

            OnUndefinedClick?.Invoke(this, e);
        }

        private void btnCategory_Click(object sender, EventArgs e)
        {
            OnCategoryClick?.Invoke(this, e);
        }

        private void cmbCase_SelectedIndexChanged(object sender, EventArgs e)
        {
            var ci = CaseInfo;

            if (ci != null)
            {
                this.lblTip.Visible = false;

                var result = CaseHelper.GetUndefinedCategory(ci.id);

                if (result.success)
                {
                    undefinedCategory = result.data;
                    this.ParentNode = result.data;
                }
            }
            else
            {
                this.lblTip.Text = "未选择所属案件";
                this.lblTip.Visible = true;
            }
        }

        public void SetCaseList(List<caseinfo> caseList)
        {
            cmbCase.Items.Clear();
            cmbCase.Items.Add("");
            foreach (var ci in CaseHelper.CaseList)
            {
                cmbCase.Items.Add(ci.case_name);
            }

            if (caseList.Count == 1)
            {
                cmbCase.SelectedIndex = 1;
            }
            else
            {
                cmbCase.SelectedIndex = -1;
            }
        }

        public HResult<FileDto> Save()
        {
            HResult<FileDto> result = new HResult<FileDto>() { success = false };
            var ci = this.CaseInfo;

            if (ci != null)
            {
                this.lblTip.Visible = false;

                result = CaseHelper.UploadFile(ci.id, this.FilePath);

                if (result.success)
                {
                    //Category.id = "";
                    //Category.name = this.FileName;
                    //Category.type = "2";
                    //Category.case_id = ci.id;
                    //Category.add_time = DateTime.Now;
                    //Category.sort = 0;
                    //Category.user_id = LoginService.User.id;
                    //Category.allow_create_folder = false;
                    //Category.allow_create_question = false;
                    //Category.allow_create_fact = false;
                    //Category.allow_create_file = false;
                    //Category.user_name = LoginService.User.real_name;
                    //Category.state = 1;

                    Category.question_id = ParentNode.parent_id;
                    Category.fact_id = ParentNode.id;
                    Category.parent_id = ParentNode.id;
                    Category.case_id = ParentNode.case_id;
                    Category.file_no = "";
                    Category.name = this.FileName;
                    Category.file_object_name = "";
                    Category.file_object_type = "";
                    if (rbtnTalkRecord.Checked)
                    {
                        Category.file_type = "1";
                    }
                    else if (rbtnPaperEvidence.Checked)
                    {
                        Category.file_type = "2";
                    }
                    else if (rbtnObjEvidence.Checked)
                    {
                        Category.file_type = "3";
                    }
                    Category.file_page_size = GetPageSize(this.FilePath);
                    Category.file_memo = "";
                    Category.available_person_ids = "";
                    Category.available_person_names = "";
                    Category.user_id = LoginService.User.id;
                    Category.files.Add(result.data);
                    Category.add_time = DateTime.Now;

                    var ret = CaseHelper.AddCaseCategory(Category);

                    if (!ret.success)
                    {
                        lblTip.Text = "保存失败，请重试";
                        lblTip.Visible = true;
                    }

                    result.success = ret.success;
                    result.message = ret.message;
                }
            }
            else
            {
                this.lblTip.Text = "未选择所属案件";
                this.lblTip.Visible = true;
            }

            return result;
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            if (this.Parent.Controls.Count == 1)
            {
                this.Parent.BackgroundImage = Properties.Resources.nofile;
            }

            System.IO.File.Delete(this.FilePath);

            this.Parent.Controls.Remove(this);
        }

        private int GetPageSize(string filePath)
        {
            int pageSize = 1;

            if (FileType == "pdf")
            {
                pageSize = GetPDFPageSize(filePath);
            }
            else if (FileType == "word")
            {
                if (Path.GetExtension(filePath) == ".doc")
                {
                    pageSize = GetDocPageSize(filePath);
                }
                else
                {
                    pageSize = GetDocxPageSize(filePath);
                }
            }
            else
            {
                pageSize = 1;
            }

            return pageSize;
        }

        private int GetDocPageSize(string filePath)
        {
            int pageSize = 1;

            try
            {
                using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    var document = new HWPFDocument(file);

                    pageSize = document.SummaryInformation.PageCount;

                    document.Dispose();

                    file.Close();
                }
            }
            catch (Exception e)
            {
            }

            return pageSize;
        }

        private int GetDocxPageSize(string filePath)
        {
            int pageSize = 1;
            try
            {
                using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    var document = new XWPFDocument(file);

                    pageSize = document.GetProperties().ExtendedProperties.Pages;

                    document.Close();
                }
            }
            catch (Exception e)
            {
            }

            return pageSize;
        }


        private int GetPDFPageSize(string filePath)
        {
            var doc = PdfReader.Open(filePath);

            int pageSize = doc.PageCount;

            doc.Close();

            return pageSize;

        }

    }
}
